package com.example.barry.udpdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import com.example.barry.udpdemo.Service.UDFClient;
import com.example.barry.udpdemo.Util.UDPSend;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;


public class MainActivity extends Activity {
    /*发送广播的按钮*/
    private Button sendUDPBrocast;

    public MulticastSocket ms;
    private TextView receive;

    private EditText ip , deviceID , shopfloorID;

    public static final String ACTION_UPDATEUI = "action.updateUI";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendUDPBrocast = (Button) findViewById(R.id.sendUDP);
       ip = (EditText) findViewById(R.id.IP);
        deviceID = (EditText) findViewById(R.id.DeviceID);
        shopfloorID = (EditText) findViewById(R.id.ShopfloorID);
       receive = (TextView) findViewById(R.id.receive) ;
        sendUDPBrocast.setOnClickListener(new SendUDPBrocastListener());
        // 为什么先启动server再启动client就可以?
        initServer();
        initClient();
    }
    public void initServer(){
        try {
            ms = new MulticastSocket();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initClient(){
        // 动态注册广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_UPDATEUI);
        UDPReceiver  broadcastReceiver = new UDPReceiver();
        registerReceiver(broadcastReceiver, filter);
        Intent intent = new Intent(MainActivity.this, UDFClient.class);
        startService(intent);

    }
    private class UDPReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getExtras().getString("IP").equals(getIpAddressString())){

            }else {
                receive.setText(intent.getExtras().getString("IP")
                        + "\n"+intent.getExtras().getString("deviceID")
                        + "\n"+intent.getExtras().getString("shopfloorID")
                );
            }
        }

    }
    /**
     * 单击按钮时，发送局域网广播
     * */
    class SendUDPBrocastListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {

            final UDPSend udpSend = new UDPSend();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    udpSend.send(ms);
                }
            }).start();
            // 接着获取实例 发送数据

        }
    }
    public static String getIpAddressString() {
        try {
            for (Enumeration<NetworkInterface> enNetI = NetworkInterface
                    .getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
                NetworkInterface netI = enNetI.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = netI
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";
    }
}
